using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;

namespace CodeStream.Testing.WebAutomation
{
    /// <summary>
    /// This is a base class for any browser lifetime management class
    /// </summary>
    [SecurityCritical]
    public abstract class BrowserInstance : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BrowserInstance"/> class.
        /// </summary>
        /// <param name="browser">The browser process created by the derived class.</param>
        protected BrowserInstance(Process browser)
        {
            Browser = browser;
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="BrowserInstance"/> is reclaimed by garbage collection.
        /// </summary>
        ~BrowserInstance()
        {
            Dispose(false);
        }

        /// <summary>
        /// Gets the browser.
        /// </summary>
        public Process Browser { get; private set; }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "The class is marked SecurityCritical instead of using LinkDemands.")]
        protected virtual void Dispose(bool disposing)
        {
            if (Browser != null)
            {
                Browser.CloseMainWindow();
                Browser = null;
            }
        }
    }
}
